package im

import (
	"fmt"
	"time"
	"strings"
	"errors"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// 聊天会话表：存储顾客和商家的会话状态等信息
type ChatSession struct {
	ChatSessionId   int64   `orm:"column(chat_session_id);pk;auto" json:"chat_session_id"` //聊天会话ID
	PartnerId       int64   `orm:"column(partner_id);index" json:"partner_id"`             //组织ID
	AppId           string  `orm:"column(app_id);size(32)" json:"app_id"`                  //托管的公众号ID
	MemberOpenId    string  `orm:"column(member_open_id)" json:"member_open_id"`           //顾客open_id
	AgentOpenId     string  `orm:"column(agent_open_id);null" json:"agent_open_id"`        //当前会话客服open_id      
	StatusId        int     `orm:"column(status_id);default(0)" json:"status_id"`          //0:等待客服;1:已接入客服;2:已过期
	AgentNewRspNum  int       `orm:"column(agent_new_rsp_num)" json:"agent_new_rsp_num"`   //客服响应客户最新一条消息的回复数量
	StartTime       time.Time `orm:"column(start_time);type(datetime)" json:"-"`           //顾客最近更新时间
	ExpireTime      time.Time `orm:"column(expire_time);type(datetime)" json:"-"`          
	IsRead          int       `orm:"column(is_read)" json:"is_read" form:"is_read"`        //消息状态ID, 1:未读, 2 已读
	//过期时间,顾客发送最后一条消息的时间+48小时   
	// 非数据库字段
	StartTimeStr   string    `orm:"-" json:"start_time"`
    ExpireTimeStr  string    `orm:"-" json:"expire_time"`
}

func init() {
	orm.RegisterModel(new(ChatSession))
}

func AddChatSession(m *ChatSession) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return id, err
}

func GetAllChatSessions(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*ChatSession,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ChatSession))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*ChatSession
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	    for _, session := range lists {
			session.StartTimeStr = session.StartTime.Format(consts.DATETIME_FORMAT)
            session.ExpireTimeStr = session.ExpireTime.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetChatSessionById(id int64) (v *ChatSession, err error) {
	o := models.GetDefaultDB()
	v = &ChatSession{ChatSessionId: id}
	if err = o.Read(v); err == nil {
		v.StartTimeStr = v.StartTime.Format(consts.DATETIME_FORMAT)
        v.ExpireTimeStr = v.ExpireTime.Format(consts.DATETIME_FORMAT)
		return v, nil
	}
	return nil, err
}

func GetChatSessionByMemberOpenId(memberOpenId string) (v *ChatSession, err error) {
	o := models.GetDefaultDB()
	v = &ChatSession{MemberOpenId: memberOpenId}
	if err = o.Read(v, "MemberOpenId"); err == nil {
		v.StartTimeStr = v.StartTime.Format(consts.DATETIME_FORMAT)
        v.ExpireTimeStr = v.ExpireTime.Format(consts.DATETIME_FORMAT)
		return v, nil
	}
	return v, err
}

func UpdateChatSessionById(m *ChatSession,param ... string) (err error) {
	o := models.GetDefaultDB()
	v := ChatSession{ChatSessionId: m.ChatSessionId}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, param...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func DeleteChatSession(id int64) (err error) {
	o := models.GetDefaultDB()
	v := ChatSession{ChatSessionId: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}


